package com.bing.search;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.FSDirectory;

import com.bing.document.GlobalFeature;
import com.bing.picture.Picture;

import net.semanticmetadata.lire.searchers.GenericDocValuesImageSearcher;
import net.semanticmetadata.lire.searchers.ImageSearchHits;
import net.semanticmetadata.lire.searchers.ImageSearcher;

public class DefaultSearchExcutor implements SearchExcutor {
	
	private static final int DEFAULT_NUM = 10;

	@Override
	public List<ExcutorResult> searchSimilar(Picture picture) {
		return this.searchSimilar(picture, GlobalFeature.LBP.getGlobalFeatureClazz());
	}

	@Override
	public List<ExcutorResult> searchSimilar(Picture picture, Class<? extends net.semanticmetadata.lire.imageanalysis.features.GlobalFeature> globalFeatureClass) {
		return this.searchSimilar(picture, globalFeatureClass, DEFAULT_NUM);
	}

	@Override
	public List<ExcutorResult> searchSimilar(Picture picture, Class<? extends net.semanticmetadata.lire.imageanalysis.features.GlobalFeature> globalFeatureClass, int pictureNum) {
		
		List<ExcutorResult> excutorResults = new ArrayList<>();
		BufferedImage img;
		try {
			img = ImageIO.read(picture.pictureInputStream());
			IndexReader indexReader = DirectoryReader.open(FSDirectory.open(Paths.get("index")));
			ImageSearcher searcher = new GenericDocValuesImageSearcher(pictureNum, globalFeatureClass, indexReader);
			ImageSearchHits imageSearchHits = searcher.search(img, indexReader);
			for (int i = 0; i < imageSearchHits.length(); i++) {
				Document document = indexReader.document(imageSearchHits.documentID(i));
				String pk = document.get("pk");
				if (pk.equals(picture.pk())) {
					continue;
				}
				ExcutorResult excutorResult = new ExcutorResult();
				excutorResult.setPk(pk);
				excutorResult.setPictureUrl(document.getField("url").stringValue());
				excutorResults.add(excutorResult);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return excutorResults;
	}

}
